﻿using CsvHelper;
using CsvHelper.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace JinYuan.Helper
{
    public class CSVHelper<T>
    {
        /// <summary>
        /// 读取CSV文件
        /// </summary>
        /// <param name="fileName">csv文件名</param>
        /// <returns></returns>
        public static List<T> ReadCSV<T>(string fileName, string strSeparator = "\t")
        {
            if (!File.Exists(fileName)) return null;

            using (var reader = new StreamReader(fileName, Encoding.Default))
            {
                var cfg = new CsvConfiguration(CultureInfo.InvariantCulture)
                {
                    Mode = CsvMode.Escape,
                    Escape = '\\',
                    Delimiter = strSeparator, // 设置分隔符号
                    HeaderValidated = null,   // 跳过表头验证
                    MissingFieldFound = null  // 忽略缺失字段
                };

                using (var csv = new CsvReader(reader, cfg))
                {
                    var list = csv.GetRecords<T>().ToList();
                    return list;
                }
            }
        }


        /// <summary>
        /// 写入CSV文件
        /// </summary>
        /// <param name="fileName">csv文件名</param>
        /// <returns></returns>
        public static bool WriterCSV(string fileName, List<T> records)
        {
            try
            {
                FileStream Log = null;
                if (!Directory.Exists(fileName))
                    Directory.CreateDirectory(fileName);
                string file = (fileName + DateTime.Now.ToString("yyyyMMdd")) + ".csv";
                var cfg = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
                if (!File.Exists(file))
                {
                    Log = new FileStream(file, FileMode.Create);
                }
                else
                {
                    cfg.HasHeaderRecord = false;//是否将第一行作为标题
                }
                if (Log != null)
                {
                    Log.Close();
                }
                //Nuget获取CsvHelper
                using (var writer = new StreamWriter(file, true, Encoding.Default))
                {
                    using (var csv = new CsvWriter(writer, cfg))
                    {
                        csv.WriteRecords(records);
                        writer.Flush();
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }


        /// <summary>
        /// 写入指定列表CSV文件
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="fileName"></param>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static bool WriterCSV(string directory, string fileName, string title, string content)
        {
            FileStream fs = null;
            StreamWriter sw = null;

            try
            {
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                string fullFileName = $@"{directory}\{fileName}";
                if (!File.Exists(fullFileName))
                {
                    fs = new FileStream(fullFileName, FileMode.Create, FileAccess.Write);
                    sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.WriteLine(title);
                }
                else
                {
                    fs = new FileStream(fullFileName, FileMode.Append, FileAccess.Write);
                    sw = new StreamWriter(fs, Encoding.UTF8);
                }

                sw.WriteLine(content);

                sw.Close();
                fs.Close();

                return true;
            }
            catch (Exception ex)
            {
                sw?.Close();
                fs?.Close();
            }

            return false;
        }


        /// <summary>
        /// 获取当天的日期的文件
        /// </summary>
        /// <param name="CurrPath"></param>
        /// <returns></returns>
        public static List<string> FindTodayFile(string CurrPath)
        {
            try
            {
                if (!Directory.Exists(CurrPath))
                {
                    return null;
                }
                DirectoryInfo di = new DirectoryInfo(CurrPath);
                FileInfo[] ffis = di.GetFiles();
                string today = DateTime.Now.Year.ToString().Substring(0, 4) + DateTime.Now.Month.ToString("0#") + DateTime.Now.Day.ToString("0#");
                List<string> listFilePath = new List<string>();

                for (int i = 0; i < ffis.Length; i++)
                {
                    FileInfo tmp = ffis[i];
                    if (tmp.Name.Substring(0, 8) == today)
                    {
                        listFilePath.Add(tmp.FullName);
                    }
                }
                return (listFilePath.Count > 0) ? listFilePath : null;
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="CurrPath"></param>
        /// <returns></returns>
        public static List<string> FindHostFile(string CurrPath, DateTime date)
        {
            try
            {
                if (!Directory.Exists(CurrPath))
                {
                    return null;
                }
                DirectoryInfo di = new DirectoryInfo(CurrPath);
                FileInfo[] ffis = di.GetFiles();
                string today = date.ToString().Substring(0, 4) + date.Month.ToString("0#") + date.Day.ToString("0#");
                //var result1 = Regex.Replace(date, @"[^0-9]+", "");
                //string today = result1.Substring(0,8);
                List<string> listFilePath = new List<string>();

                for (int i = 0; i < ffis.Length; i++)
                {
                    FileInfo tmp = ffis[i];
                    if (tmp.Name.Substring(0, 8) == today)
                    {
                        listFilePath.Add(tmp.FullName);
                    }
                }
                return (listFilePath.Count > 0) ? listFilePath : null;
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }


        /// <summary>
        /// 导出到CSV文件
        /// </summary>
        /// <param name="table">报表DataTable</param>
        /// <param name="filePath">导出路径</param>
        /// <param name="msg">输出信息</param>
        /// <param name="columnName">自定义的列名称，以','英文逗号分隔</param>
        /// <param name="tableHeader">表名，一般为空</param>
        /// <returns>是否导出成功</returns>
        public static bool ExportDataTableToCSV(DataTable table, string filePath, out string msg, string columnName = null, string tableHeader = null)
        {
            try
            {
                string dirPath = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);//文件的父目录不存在就创建新目录
                }
                bool IsAppend = false; //false为创建 true为追加
                if (File.Exists(filePath))
                {
                    IsAppend = true;//如果文件存在就不写入表头
                }
                using (FileStream _stream = new FileStream(filePath, FileMode.Create | FileMode.Append, FileAccess.Write))
                {
                    StreamWriter _writer = new StreamWriter(_stream, Encoding.UTF8);
                    if (tableHeader != null)
                    {
                        _writer.WriteLine(tableHeader);
                    }

                    if (columnName != null && !IsAppend)
                    {
                        _writer.WriteLine(columnName);
                    }
                    else if (columnName == null && !IsAppend)
                    {
                        List<string> columnNameList = new List<string>();
                        foreach (DataColumn dc in table.Columns)
                        {
                            columnNameList.Add(dc.ColumnName);
                        }
                        _writer.WriteLine(string.Join(",", columnNameList));
                    }

                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        for (int j = 0; j < table.Columns.Count; j++)
                        {
                            _writer.Write(table.Rows[i][j].ToString());
                            _writer.Write(",");
                        }
                        _writer.WriteLine();
                    }
                    _writer.Close();
                    msg = "导出CSV文件成功";
                    return true;
                }
            }
            catch (Exception ex)
            {
                msg = string.Format("导出CSV文件失败，原因：{0}", ex.Message);
                return false;
            }
        }


        /// <summary>
        /// 导出报表为Csv
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="strFilePath">物理路径</param>
        /// <param name="tableheader">表头</param>
        /// <param name="columname">字段标题,逗号分隔</param>
        public static bool dt2csv(DataTable dt, string strFilePath, string tableheader, string columname)
        {
            try
            {
                string strBufferLine = "";
                StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8);
                strmWriterObj.WriteLine(tableheader);
                strmWriterObj.WriteLine(columname);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strBufferLine = "";
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j > 0)
                            strBufferLine += ",";
                        strBufferLine += dt.Rows[i][j].ToString();
                    }
                    strmWriterObj.WriteLine(strBufferLine);
                }
                strmWriterObj.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 将Csv读入DataTable
        /// </summary>
        /// <param name="filePath">csv文件路径</param>
        /// <param name="n">表示第n行是字段title,第n+1行是记录开始</param>
        public static DataTable csv2dt(string filePath, int n, DataTable dt)
        {
            StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, false);
            int i = 0, m = 0;
            reader.Peek();
            while (reader.Peek() > 0)
            {
                m = m + 1;
                string str = reader.ReadLine();
                if (m >= n + 1)
                {
                    string[] split = str.Split(',');

                    System.Data.DataRow dr = dt.NewRow();
                    for (i = 0; i < split.Length; i++)
                    {
                        dr[i] = split[i];
                    }
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

    }
}
